<template>
    <div class="content_main">
        <div class="nav_box">
            <nav>
                <p @click="changeNav(0)" :class="{active:class_id == 0}" >推薦</p>
                <p v-for="item,index in theateListClass" :key='item.id' :class="{active:class_id == item.id}" @click="changeNav(item.id)">{{item.class_name}}</p>
            </nav>
            <div class="input">
                <el-input @input="handleSearch" @keyup.enter='searchSand' clearable class="input-with-select" prefix-icon="search" style="height: 40px;width: 400px;" v-model="search_input" :placeholder="$t('search_value')">
                    <template #append>
                        <el-button @click="searchSand">搜索</el-button>
                    </template>
                </el-input>
            </div>
        </div>
        
        <div class="main" v-show="!search_input">
            <div class="main_item" v-for="item in theateList" :key="item.id" @click="toPages(item.id)">
                <div class="cover">
                    <img :src="$baseUrl+item.theater_img" alt="">
                    <div class="tag" v-if="item.is_free == 1">免費</div>
					<div class="tagVip" v-if="item.is_free !== 1 && item.is_free !== 2 && item.is_pay != 1">付費</div>
                    <div class="tagVip isPay" v-if="item.is_pay == 1">已解鎖</div>
                    <div class="episode">{{item.sum_episode}}集全</div>
                    <div class="sum_time">{{formatDuration(item.sum_time)}}</div>
					<!-- <div class="looks">151人觀看</div> -->
                </div>
                <div class="title">{{ item.theater_name }}</div>
                <div class="tags">
                    <span v-for="tag in item.theater_tag.split(/[,;]\s*/)" :key="tag">{{ tag }}</span>
                </div>
            </div>
        </div>

        <div class="main" v-show="search_input">
            <div class="main_item" v-for="item in searchList" :key="item.id" @click="toPages(item.id)">
                <div class="cover">
                    <img :src="$baseUrl+item.theater_img" alt="">
                    <div class="tag" v-if="item.is_free == 1">免費</div>
					<div class="tagVip" v-if="item.is_free !== 1 && item.is_free !== 2 && item.is_pay != 1">付費</div>
                    <div class="tagVip isPay" v-if="item.is_pay == 1">已購買</div>
                    <div class="episode">{{item.sum_episode}}集全</div>
                    <div class="sum_time">{{formatDuration(item.sum_time)}}</div>
					<!-- <div class="looks">151人觀看</div> -->
                </div>
                <div class="title">{{ item.theater_name }}</div>
                <div class="tags">
                    <span v-for="tag in item.theater_tag.split(/[,;]\s*/)" :key="tag">{{ tag }}</span>
                </div>
            </div>
        </div>
        <el-empty class="empty" :image-size="200" v-show="!searchList.length && search_input" description="暫未搜索到结果" />
        <!-- From Uiverse.io by satyamchaudharydev --> 
        <!-- <div class="loading" v-if="hasMore">
            <span v-for="item in 5"></span>
        </div> -->
    </div>
</template>

<script setup>
	import axios from '@/utils/api'
    import { useRouter } from 'vue-router'
    import { useUserInfoStore } from '@/store/modules/user_info/index';
    import { useIsShowLogin } from "@/store/modules/isShowLogin/index.js";
    const user_infoStore = useUserInfoStore();
    const isShowLoginStore = useIsShowLogin();
    let user_info = reactive(user_infoStore.userInfo)
    const userid = user_info.id || ''
    const router = useRouter()
    const class_id = ref(0)
    const page = ref(1)
    const limit = ref(28)

	const changeNav = (id) => {
        if(id == class_id.value) return
		class_id.value = id
        getTheateList()
	}

    const theateListClass = ref([])
	const getTheateListClass = async () => {
		const res = await axios.get('/getTheaterClass?type=4')
		if (res.code == 200) {
			theateListClass.value = res.data
            getTheateList()
		} else {
			ElMessage.error(res.message)
		}
	}
	getTheateListClass()

    const theateList = ref([])
	const getTheateList = async (classide) => {
        let classId = classide === 0 ? classide : class_id.value
        page.value = 1
        hasMore.value = true
        
		const res = await axios.get(`/theaterList?class_id=${classId}&theater_name=${search_input.value}&page=${page.value}&limit=${limit.value}&user_id=${userid}`)
		if (res.code == 200) {
            const list = res.data.data
            if (list.length < limit.value) hasMore.value = false
            if(search_input.value){
                searchList.value = list
            }else{
                theateList.value = list
            }
			window.addEventListener('scroll', handleScroll)
		} else {
			ElMessage.error(res.message)
		}
	}
	

    const search_input = ref('')
    let debounceTimer = null
    const hisClassId = ref('')
    const hisPage = ref(0)
    const hisMore = ref(false)
    const handleSearch = (val) => {
        if(val && hisPage.value == 0){
            hisPage.value = page.value
            hisMore.value = hasMore.value
        }
        page.value = 1
        clearTimeout(debounceTimer)
        debounceTimer = setTimeout(() => {
            if (val === '') {
                class_id.value = hisClassId.value
                if(theateList.value.length <= limit.value){
                    hasMore.value = false
                }else{
                    hasMore.value = true
                }
                page.value = hisPage.value
                hasMore.value = hisMore.value
                searchList.value = []
            } else {
                hisClassId.value = class_id.value
                hasMore.value = false
                getTheateList(0)
            }
        }, 500) // 500ms 防抖时间
    }
    const searchSand = () => {
        getTheateList(0)
    }

    const toPages = (id) => {
        if(!userid){
            ElMessage.warning('請先登入')
            isShowLoginStore.showLogin();
        }else{
            router.push('/home/SandSculptureMain?id='+id)
        }
        
    }

    const searchList = ref([])


    const isLoading = ref(false)
    const hasMore = ref(true)

    const handleScroll = () => {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
        const windowHeight = window.innerHeight
        const documentHeight = document.documentElement.scrollHeight
        console.log(scrollTop + windowHeight , documentHeight - 100);
        
        if (scrollTop + windowHeight >= documentHeight - 100) {
            loadMore()
        }
    }

    const loadMore = async () => {
        console.log('加载更多数据...',hasMore.value);
        
        if (isLoading.value || !hasMore.value) return
        isLoading.value = true
        page.value += 1
        const res = await axios.get(`/theaterList?class_id=${class_id.value}&theater_name=${search_input.value}&page=${page.value}&limit=${limit.value}&user_id=${userid}`)
        if (res.code === 200) {
            const list = res.data.data
            if (list.length < limit.value) hasMore.value = false

            if (search_input.value) {
                searchList.value.push(...list)
            } else {
                theateList.value.push(...list)
            }
        } else {
            ElMessage.error(res.message)
        }
        isLoading.value = false
    }

    // onMounted(() => {
    //     window.addEventListener('scroll', handleScroll)
    // })

    onUnmounted(() => {
        window.removeEventListener('scroll', handleScroll)
    })

    const formatDuration = (seconds) => {
        seconds = Number(seconds);
        if (isNaN(seconds) || seconds < 0) return '00:00';

        const h = Math.floor(seconds / 3600);
        const m = Math.floor((seconds % 3600) / 60);
        const s = seconds % 60;

        const pad = (n) => String(n).padStart(2, '0');

        if (h > 0) {
            return `${pad(h)}:${pad(m)}:${pad(s)}`;
        } else {
            return `${pad(m)}:${pad(s)}`;
        }
    };

</script>

<style lang="less" scoped>
	.content_main{
        width: 90%;
        .nav_box{
            display: flex;
            align-items: center;
            .input{
                margin-left: 0;
                position: relative;
                top: -2px;
            }
        }
        nav{
            display: flex;
            justify-content: space-around;
            padding: 10px 0 10px 0;
            margin-top: 10px;
            margin-bottom: 15px;
            p:first-child{
                position: relative;
            }
            p:first-child::before{
                content: '';
                background-image: url();
                background-size: 54%;
                background-repeat: no-repeat;
                background-position: center;
                position: absolute;
                top: -53px;
                left: -9px;
                z-index: -1;
                width: 115px;
                height: 115px;
            }
            p{
                width: 100px;
                height: 40px;
                line-height: 40px;
                text-align: center;
                border-radius: 20px;
                cursor: pointer;
                color: rgb(73, 73, 73);
                user-select: none;
                transition: all .3s;
                &.active{
                    font-size: 19px;
                    color: black;
                    font-weight: bold;
                    position: relative;
                    &::after {
                        content: "";
                        position: absolute;
                        left: 50%;
                        bottom: 1px;
                        width: 20%;
                        height: 3px;
                        background: @primary-color; 
                        transform: translateX(-50%);
                        border-radius: 10px;
                        transition: all .3s;
                    }
                }
                &:hover{
                    // font-size: 20px;
                    color: black;
                    // font-weight: 600;
                }
            }

        }
        .main{
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); // 自适应列宽
            row-gap: 30px;
            column-gap: 15px;
            margin-bottom: 40px;
            .main_item{
                margin: 0;
                cursor: pointer;
                .cover{
                    overflow: hidden;
                    border-radius: 12px;
                    display: flex;
                    position: relative;
                    width: 230px;
                    height: 290px;
                    img{
                        width: 100%;
                        height: 100%;  // 新增
                        object-fit: cover; // 新增(保持比例填充)
                        border-radius: 12px;
                        transition: all .3s;
                    }
                    .tag {
                        background: linear-gradient(to right, #adf4cc, #60e8a1);
                        display: inline-block;
                        position: absolute;
                        right: 0;
                        top: 0;
                        padding: 2px 10px;
                        border-radius: 0 12px 0 12px;
                        font-size: 12px;
                    }

                    .tagVip {
                        background: linear-gradient(to right, #fce7b4, #fab660);
                        display: inline-block;
                        position: absolute;
                        right: 0;
                        top: 0;
                        padding: 2px 10px;
                        border-radius: 0 12px 0 12px;
                        font-size: 12px;
                    }
                    .isPay{
						background: linear-gradient(to right, #b4e7fc, #60cdfa);
					}
                    .episode {
                        color: white;
                        position: absolute;
                        bottom: 7px;
                        right: 7px;
                        // font-weight: bold;
                        font-size: 12px;
                        filter: drop-shadow(2px 4px 6px black);
                    }

                    .looks {
                        color: white;
                        position: absolute;
                        top: 5px;
                        left: 5px;
                        // font-weight: bold;
                        font-size: 12px;
                        filter: drop-shadow(2px 4px 6px rgb(117, 117, 117));
                    }
                    .sum_time{
                        color: white;
                        position: absolute;
                        bottom: 7px;
                        left: 7px;
                        // font-weight: bold;
                        font-size: 12px;
                        filter: drop-shadow(2px 4px 6px rgb(117, 117, 117));
                    }
                }
                .cover:hover{
                    img{
                        transform: scale(1.05);
                    }
                }
                .title{
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    width: 100%;
                    margin-top: 6px;
                    font-weight: bold;
                    color: #303030;
                    
                }
                .tags{
                    height: 30px;
                    overflow: hidden;
                    display: flex;
                    flex-wrap: wrap;
                    align-items: center;
                    flex-direction: row;
                    justify-content: flex-start;
                    row-gap: 10px;
                    margin-top: 6px;
                    span{
                        align-items: center;
                        background-color: #e5e5e5;
                        border-radius: 4px;
                        color: #313131;
                        display: flex;
                        flex-shrink: 0;
                        font-size: 12px;
                        height: 20px;
                        margin-right: 4px;
                        padding: 2px 6px;
                        margin-left: 0;
                    }
                }
            }
            .empty{
                margin: 0 auto;
            }
        }
    }

    /* From Uiverse.io by satyamchaudharydev */ 
    .loading {
        --speed-of-animation: 0.9s;
        --gap: 6px;
        --first-color: #4c86f9;
        --second-color: #49a84c;
        --third-color: #f6bb02;
        --fourth-color: #f6bb02;
        --fifth-color: #2196f3;
        display: flex;
        justify-content: center;
        align-items: center;
        width: 50px;
        gap: 6px;
        height: 50px;
        margin-bottom: 20px;
    }

    .loading span {
        width: 4px;
        height: 50px;
        background: var(--first-color);
        animation: scale var(--speed-of-animation) ease-in-out infinite;
    }

    .loading span:nth-child(2) {
        background: var(--second-color);
        animation-delay: -0.8s;
    }

    .loading span:nth-child(3) {
        background: var(--third-color);
        animation-delay: -0.7s;
    }

    .loading span:nth-child(4) {
        background: var(--fourth-color);
        animation-delay: -0.6s;
    }

    .loading span:nth-child(5) {
        background: var(--fifth-color);
        animation-delay: -0.5s;
    }

    @keyframes scale {
        0%, 40%, 100% {
        transform: scaleY(0.05);
    }

    20% {
        transform: scaleY(1);
    }
}
</style>